<?php

class ZFPainel_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{

    /**
     *
     * @var ZFPainel_Acl
     */
    private $acl;

    public function __construct(array $options = array())
    {
        $this->acl = $options['acl'];
    }

    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {

        if (($request->getParam('strategyController') == 'out') || ($request->getParam('controller') == 'out')) {
            return;
        }

        if (!ZFPainel_Auth::getInstance()->hasIdentity()) {
            $front = Zend_Controller_Front::getInstance();

            $url = $front->getRouter()->assemble(array(
                'tela' => 'OUTFRM001'
                    ), 'RotaTela', false, false);

            $front
                    ->getResponse()
                    ->setRedirect($url)
                    ->sendHeaders()
            ;
            exit;
        } else {
            $params = $request->getParams();
            try {
                if ($params['controller'] == 'tela') {
                    $this->acl->checkPermission($params['tela'], $params);
                } elseif ($params['controller'] == 'index') {
                    $this->acl->checkPermission('INDLIS001', $params);
                } else {
                    $this->acl->checkPermission($params['controller'] . '/' . $params['id'], $params);
                }
            } catch (ZFPainel_Exception_Auth_Unauthorized $exc) {
                throw new Zend_Controller_Action_Exception($exc->getMessage(), 403, $exc);
            } catch (ZFPainel_Exception_Resource_NotFound $exc) {
                throw new Zend_Controller_Action_Exception($exc->getMessage(), 403, $exc);
            } catch (Exception $exc) {
                die($exc);
                throw new Zend_Controller_Action_Exception($exc->getMessage(), 500);
            }
        }
    }

}
